<template>
  <el-card class="task-card" shadow="hover">
    <!-- 任务头部 -->
    <div class="card-header">
      <div class="task-info">
        <div class="task-status">
          <el-dropdown 
            v-if="canManage"
            trigger="click" 
            @command="handleStatusChange"
          >
            <el-tag 
              :type="getStatusType(task.status)" 
              class="status-tag clickable"
            >
              {{ getStatusLabel(task.status) }}
              <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-tag>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item 
                  v-for="status in statusOptions"
                  :key="status.value"
                  :command="status.value"
                  :disabled="status.value === task.status"
                >
                  <el-tag :type="getStatusType(status.value)" size="small">
                    {{ status.label }}
                  </el-tag>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-tag 
            v-else
            :type="getStatusType(task.status)"
          >
            {{ getStatusLabel(task.status) }}
          </el-tag>
        </div>
        
        <div class="task-priority">
          <el-tag 
            :type="getPriorityType(task.priority)" 
            size="small"
            effect="plain"
          >
            {{ getPriorityLabel(task.priority) }}
          </el-tag>
        </div>
      </div>
      
      <div class="card-actions" v-if="canManage">
        <el-dropdown trigger="click" @command="handleCommand">
          <el-button :icon="MoreFilled" size="small" text />
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="edit" :icon="Edit">
                {{ $t('common.edit') }}
              </el-dropdown-item>
              <el-dropdown-item command="delete" :icon="Delete" divided>
                {{ $t('common.delete') }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 任务标题和描述 -->
    <div class="card-content">
      <h4 class="task-title">{{ task.title }}</h4>
      <p class="task-description" v-if="task.description">
        {{ truncateText(task.description, 120) }}
      </p>
    </div>

    <!-- 任务分配和时间信息 -->
    <div class="card-meta">
      <!-- 分配者信息 -->
      <div class="assignee-info">
        <span class="meta-label">{{ $t('project.assignee') }}:</span>
        <div class="assignee-content">
          <el-dropdown 
            v-if="canManage"
            trigger="click" 
            @command="handleAssigneeChange"
          >
            <div class="assignee-display clickable">
              <el-avatar
                v-if="assignee"
                :size="24"
                :src="assignee.avatarUrl"
              >
                {{ (assignee.username || assignee.nickname || 'U')?.charAt(0).toUpperCase() }}
              </el-avatar>
              <el-icon v-else><User /></el-icon>
              <span>{{ assignee?.username || assignee?.nickname || $t('project.unassigned') }}</span>
              <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="unassign">
                  <div class="member-option">
                    <el-icon><User /></el-icon>
                    <span>{{ $t('project.unassigned') }}</span>
                  </div>
                </el-dropdown-item>
                <el-dropdown-item 
                  v-for="member in teamMembers"
                  :key="member.userId"
                  :command="member.userId"
                  :disabled="member.userId === task.assigneeId"
                >
                  <div class="member-option">
                    <el-avatar :size="20" :src="member.avatarUrl">
                      {{ (member.username || member.nickname || 'U')?.charAt(0).toUpperCase() }}
                    </el-avatar>
                    <span>{{ member.username || member.nickname || `用户${member.userId}` }}</span>
                  </div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <div v-else class="assignee-display">
            <el-avatar
              v-if="assignee"
              :size="24"
              :src="assignee.avatarUrl"
            >
              {{ (assignee.username || assignee.nickname || 'U')?.charAt(0).toUpperCase() }}
            </el-avatar>
            <el-icon v-else><User /></el-icon>
            <span>{{ assignee?.username || assignee?.nickname || $t('project.unassigned') }}</span>
          </div>
        </div>
      </div>

      <!-- 截止日期 -->
      <div class="due-date-info" v-if="task.dueDate">
        <span class="meta-label">{{ $t('project.dueDate') }}:</span>
        <div class="due-date-content" :class="{ overdue: isOverdue, warning: isNearDeadline }">
          <el-icon><Calendar /></el-icon>
          <span>{{ formatDate(task.dueDate) }}</span>
          <el-icon v-if="isOverdue" class="overdue-icon"><Warning /></el-icon>
        </div>
      </div>

      <!-- 工时信息 -->
      <div class="hours-info" v-if="task.estimatedHours || task.actualHours">
        <span class="meta-label">{{ $t('project.hours') }}:</span>
        <div class="hours-content">
          <span v-if="task.estimatedHours">
            {{ $t('project.estimated') }}: {{ task.estimatedHours }}h
          </span>
          <span v-if="task.actualHours" class="actual-hours">
            {{ $t('project.actual') }}: {{ task.actualHours }}h
          </span>
        </div>
      </div>
    </div>

    <!-- 任务底部信息 -->
    <div class="card-footer">
      <div class="task-dates">
        <span class="created-date">
          {{ $t('common.created') }}: {{ formatRelativeTime(task.createdAt) }}
        </span>
        <span v-if="task.completedAt" class="completed-date">
          {{ $t('project.completed') }}: {{ formatRelativeTime(task.completedAt) }}
        </span>
      </div>
      
      <div class="task-tags">
        <el-tag 
          v-if="isOverdue" 
          type="danger" 
          size="small"
          effect="dark"
        >
          {{ $t('project.overdue') }}
        </el-tag>
        <el-tag 
          v-if="isNearDeadline && !isOverdue" 
          type="warning" 
          size="small"
        >
          {{ $t('project.nearDeadline') }}
        </el-tag>
        <el-tag 
          v-if="task.status === 'COMPLETED'" 
          type="success" 
          size="small"
        >
          {{ $t('project.completed') }}
        </el-tag>
      </div>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import {
  MoreFilled,
  Edit,
  Delete,
  ArrowDown,
  User,
  Calendar,
  Warning
} from '@element-plus/icons-vue'
import type { Task } from '@/types/project'
import { TaskStatus, TaskPriority } from '@/types/project'
import { formatDate, formatRelativeTime } from '@/utils/date'

// Props
interface Props {
  task: Task
  canManage: boolean
  teamMembers: Array<{
    userId: number
    username?: string
    nickname?: string
    avatarUrl?: string
    role: string
    status: string
  }>
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  edit: [task: Task]
  delete: [task: Task]
  statusChange: [task: Task, status: string]
  assign: [task: Task, assigneeId: number]
}>()

const { t } = useI18n()

// 计算属性
const assignee = computed(() => {
  if (!props.task.assigneeId) return null
  return props.teamMembers.find(member => member.userId === props.task.assigneeId)
})

const isOverdue = computed(() => {
  if (!props.task.dueDate || props.task.status === 'COMPLETED') return false
  return new Date(props.task.dueDate) < new Date()
})

const isNearDeadline = computed(() => {
  if (!props.task.dueDate || props.task.status === 'COMPLETED' || isOverdue.value) return false
  const dueDate = new Date(props.task.dueDate)
  const now = new Date()
  const diffDays = Math.ceil((dueDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
  return diffDays <= 3 && diffDays > 0
})

const statusOptions = computed(() => [
  { value: TaskStatus.TODO, label: t('project.status.todo') },
  { value: TaskStatus.IN_PROGRESS, label: t('project.status.inProgress') },
  { value: TaskStatus.REVIEW, label: t('project.status.review') },
  { value: TaskStatus.COMPLETED, label: t('project.status.completed') },
  { value: TaskStatus.CANCELLED, label: t('project.status.cancelled') }
])

// 方法
const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    'TODO': 'info',
    'IN_PROGRESS': 'warning',
    'REVIEW': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  }
  return types[status] || 'info'
}

const getStatusLabel = (status: string) => {
  const labels: Record<string, string> = {
    'TODO': t('project.status.todo'),
    'IN_PROGRESS': t('project.status.inProgress'),
    'REVIEW': t('project.status.review'),
    'COMPLETED': t('project.status.completed'),
    'CANCELLED': t('project.status.cancelled')
  }
  return labels[status] || status
}

const getPriorityType = (priority: string) => {
  const types: Record<string, string> = {
    'LOW': '',
    'MEDIUM': 'warning',
    'HIGH': 'danger',
    'URGENT': 'danger'
  }
  return types[priority] || ''
}

const getPriorityLabel = (priority: string) => {
  const labels: Record<string, string> = {
    'LOW': t('project.priority.low'),
    'MEDIUM': t('project.priority.medium'),
    'HIGH': t('project.priority.high'),
    'URGENT': t('project.priority.urgent')
  }
  return labels[priority] || priority
}

const truncateText = (text: string, maxLength: number) => {
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

const handleCommand = (command: string) => {
  switch (command) {
    case 'edit':
      emit('edit', props.task)
      break
    case 'delete':
      emit('delete', props.task)
      break
  }
}

const handleStatusChange = (status: string) => {
  emit('statusChange', props.task, status)
}

const handleAssigneeChange = (command: string | number) => {
  if (command === 'unassign') {
    // 取消分配
    emit('assign', props.task, 0)
  } else {
    emit('assign', props.task, command as number)
  }
}
</script>

<style scoped lang="scss">
.task-card {
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 16px;

    .task-info {
      display: flex;
      gap: 12px;
      align-items: center;

      .status-tag {
        &.clickable {
          cursor: pointer;
          
          &:hover {
            opacity: 0.8;
          }
        }
      }
    }

    .card-actions {
      opacity: 0;
      transition: opacity 0.3s ease;
    }
  }

  &:hover .card-actions {
    opacity: 1;
  }

  .card-content {
    margin-bottom: 16px;

    .task-title {
      margin: 0 0 8px 0;
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      line-height: 1.4;
    }

    .task-description {
      margin: 0;
      font-size: 14px;
      color: var(--el-text-color-regular);
      line-height: 1.5;
    }
  }

  .card-meta {
    margin-bottom: 16px;
    display: flex;
    flex-direction: column;
    gap: 12px;

    .meta-label {
      font-size: 12px;
      color: var(--el-text-color-secondary);
      font-weight: 500;
      margin-right: 8px;
    }

    .assignee-info,
    .due-date-info,
    .hours-info {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .assignee-display {
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 14px;

      &.clickable {
        cursor: pointer;
        padding: 4px 8px;
        border-radius: 4px;
        transition: background-color 0.3s ease;

        &:hover {
          background-color: var(--el-bg-color-page);
        }
      }
    }

    .due-date-content {
      display: flex;
      align-items: center;
      gap: 4px;
      font-size: 14px;
      color: var(--el-text-color-regular);

      &.warning {
        color: var(--el-color-warning);
      }

      &.overdue {
        color: var(--el-color-danger);
        font-weight: 600;

        .overdue-icon {
          animation: pulse 2s infinite;
        }
      }
    }

    .hours-content {
      display: flex;
      gap: 12px;
      font-size: 14px;
      color: var(--el-text-color-regular);

      .actual-hours {
        color: var(--el-color-primary);
        font-weight: 500;
      }
    }
  }

  .card-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 12px;
    border-top: 1px solid var(--el-border-color-lighter);

    .task-dates {
      display: flex;
      flex-direction: column;
      gap: 4px;
      font-size: 11px;
      color: var(--el-text-color-placeholder);
    }

    .task-tags {
      display: flex;
      gap: 6px;
    }
  }
}

.member-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 1;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .task-card {
    .card-meta {
      .assignee-info,
      .due-date-info,
      .hours-info {
        flex-direction: column;
        align-items: flex-start;
      }
    }

    .card-footer {
      flex-direction: column;
      gap: 12px;
      align-items: flex-start;
    }
  }
}
</style>
